<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>菜单管理</title>
        <meta name="renderer" content="webkit">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
        <link rel="stylesheet" href="../../lib/layui/css/layui.css" media="all">
        <link rel="stylesheet" href="../../lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
        <link rel="stylesheet" href="../../css/public.css" media="all">
<style>
    .custom-tree-item-clicked{color:#FC9003}
</style>
    </head>
    <body>
        <div class="layui-form " lay-filter="test1" >
            <div style="width:28%; float:left;">
                <fieldset class="layui-elem-field layui-field-title" style="margin-top: 20px;">
                    <legend>菜单列表</legend>
                </fieldset>
                <div style="display: inline-block; width: 80%; height: 400px; padding: 10px; border: 1px solid #ddd; overflow: auto;">

                    <ul id="menu-tree" class="layui-tree-main custom-tree-item-clicked"></ul>
                </div>
            </div>
            <div style="width:70%;float:right;">
                <fieldset class="layui-elem-field layui-field-title" style="margin-top: 22px;">
                    <legend>菜单详情</legend>
                </fieldset>
                <form class="layui-form layui-form-pane" id="myForm" name="myForm" onsubmit="return false;"
                      lay-filter="myForm">
                    <input type="hidden" id="id" name="id">
                    <div class="layui-form-item">
                        <label class="layui-form-label">菜单名称</label>
                        <div class="layui-input-block">
                            <input type="text" id="title" name="title" autocomplete="off" required lay-verify="required"
                                   data-tips-error-required="菜单名称不能为空" placeholder="请输入菜单名称" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">连接地址</label>
                        <div class="layui-input-block">
                            <input type="text" id="href" name="href" required lay-verify="required" autocomplete="off"
                                   placeholder="请输入菜单地址" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">菜单图标</label>
                            <div class="layui-input-inline">
                                <input type="text" id="icon" name="icon" autocomplete="off" placeholder="请选则菜单图标" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <span id="spanid" ></span>
                        </div>
                        <div class="layui-inline">
                            <div class="layui-input-inline">
                                <input type="text" id="iconPicker" value="" lay-filter="iconPicker" class="hide">
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">菜单排序号</label>
                        <div class="layui-input-block">
                            <input type="text" id="sort" name="sort" required lay-verify="required" autocomplete="off"
                                   placeholder="请输入菜单序号" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">备注</label>
                        <div class="layui-input-block">
                            <input type="text" id="remark" name="remark" autocomplete="off" placeholder="请输入备注"
                                   class="layui-input">
                        </div>
                    </div>
                    <div class="layui-form-item" lay-filter="">
                        <div class="layui-form-item">
                            <div class="layui-input-block">
                                <button class="layui-btn" lay-submit lay-filter="modify">修改</button>
                                <button class="layui-btn" id="add" lay-filter="add">新增</button>
<!--                                <button class="layui-btn" lay-filter="add" onclick="add()">新增</button>-->
                                <button class="layui-btn" lay-submit lay-filter="del">删除</button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
        <script src="../../lib/layui/layui.js" charset="utf-8"></script>
        <script src="../../js/provider/my-utils.js" charset="utf-8"></script>
        <script src="../../js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script>
     var menulist;//全部菜单不经过父子级处理
     var datalist;//全部菜单经过父子级处理
     //获取全部的菜单并且树形结构处理

    layui.use(['tree', 'layer','form','table','iconPickerFa'], function () {
        var layer = layui.layer,
            $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            iconPickerFa = layui.iconPickerFa,
            tree = layui.tree;

        iconPickerFa.render({
            // 选择器，推荐使用input
            elem: '#iconPicker',
            // fa 图标接口
            url: "../../lib/font-awesome-4.7.0/less/variables.less",
            // 是否开启搜索：true/false，默认true
            search: true,
            // 是否开启分页：true/false，默认true
            page: true,
            // 每页显示数量，默认12
            limit: 12,
            // 点击回调
            click: function (data) {
                console.log(data);
                $("#icon").val(data.icon);
            },
            // 渲染成功后的回调
            success: function (d) {
                console.log(d);
            }
        });
        var renderTable = function () {
            $.ajax({
                url: "/channel/sys-menu/ALL",
                type: 'POST',
                headers: {
                    'Accept': 'application/json',
                    'Authorization': 'Bearer ' + JSON.parse(localStorage.getItem('userdetail')).token
                },
                success: function (data) {
                    datalist = data;
                    menulist = data;
                    console.log("datalist", datalist);
                    for (var o in datalist) {
                        datalist[o].name = datalist[o].title;
                        datalist[o].spread = true;
                    }
                    datalist = transData(data, "id", "pid", "children");
                    tree.render({
                        elem: '#menu-tree' //指定元素
                        , id: 'demoId1'
                        , data: datalist
                        , isJump: false //是否允许点击节点时弹出新窗口跳转
                        , showLine: false //是否开启连接线
                        , onlyIconControl: true//是否仅允许节点左侧图标控制展开收缩
                        , icon: {        //三种图标样式，更改几个都可以，用的是layui的图标
                            open: "layui-icon-heart"       //节点打开的图标
                            , close: "layui-icon-heart-fill"    //节点关闭的图标
                            , end: "layui-icon-logout"      //末尾节点的图标
                        }
                        , click: function (obj) {
                            var clickdata = {};
                            clickdata = obj.data;  //获取当前点击的节点数据
                            // layer.msg('状态：'+ obj.state + '<br>节点数据：' + JSON.stringify(clickdata));
                            form.val("myForm", {
                                "title": clickdata.title,
                                "icon": clickdata.icon,
                                "sort": clickdata.sort,
                                "remark": clickdata.remark,
                                "href": clickdata.href,
                                "id": clickdata.id,
                            });
                           var liicon= clickdata.icon;
                            var lihtml='<i class="fa '+liicon+'" ></i>';
                            $("#spanid").html(lihtml);

                            $(".layui-tree-set").each(function (item, value) {//设置节点的背景色
                                $(this).find(".layui-tree-txt").eq(0).css({"background-color": "transparent"});
                            });
                            $(".layui-tree-set").each(function (item, value) {//设置选中的节点的背景色
                                if($(this).attr("data-id")== clickdata.id) {
                                    $(this).find(".layui-tree-txt").eq(0).css({"background-color":"#9acfea"});
                                }
                            });
                        }
                    });
                }, error: function (data) {
                }
            });
        }
        renderTable();


        //修改
        form.on('submit(modify)', function (data) {
            var str = "确定修改菜单信息吗？";
            layer.confirm(str, {btn: ['确定', '取消'], title: "提示"}, function (index) {
                $.ajax({
                    url:"/channel/sys-menu/update",
                    type:"POST",
                    dataType: 'json',
                    data:data.field,
                    headers:{'Authorization':'Bearer '+ JSON.parse(localStorage.getItem('userdetail')).token},
                    success:function (data) {
                        layer.msg("修改成功", {
                            icon: 6,//成功的表情
                            time: 1000 //1秒关闭（如果不配置，默认是3秒）
                        });
                        tree.reload('demoId1', {});
                        Refresh();
                        renderTable();
                    },
                    error:function (data) {
                        console.log('error', data);
                        layer.msg("修改失败", {
                            icon: 6,//成功的表情
                            time: 1000 //1秒关闭（如果不配置，默认是3秒）
                        });
                    }
                });
            return false;
            });
        });
        //删除菜单
        form.on('submit(del)', function (data) {
            var str = "确定删除菜单？";
            layer.confirm(str, {btn: ['确定', '取消'], title: "提示"}, function (index) {
                    var hasValue = hasChildren(data.field.id, menulist);
                    if(hasValue== true){
                        layer.msg("父级菜单不能删除！");
                        return false;
                    }else{
                        $.ajax({
                            url: "/channel/sys-menu/del",
                            type: "POST",
                            dataType:"json",
                            data:data.field,
                            headers:{'Authorization':'Bearer '+ JSON.parse(localStorage.getItem('userdetail')).token},
                            success: function(data) {
                                layer.msg("删除菜单成功", {
                                    icon: 6,//成功的表情
                                    time: 1000 //1秒关闭（如果不配置，默认是3秒）
                                }, function () {
                                    renderTable();
                                    table.reload("currentTableId");
                                });
                            },
                            error:function (data) {
                                console.log("error", JSON.stringify(data));
                                layer.msg("删除菜单失败");
                            }
                        });
                        return false;
                    }
            });
        });
        //新增
        $(document).on('click','#add',function (obj) {
            var id = $("#id").val();
            if (id == undefined || id == '') {
                layer.msg("请选择上级菜单", {
                    icon: 6,//成功的表情
                    time: 1000 //1秒关闭（如果不配置，默认是3秒）
                });
                return false;
            }else{
                var index = layer.open({
                    title: '新增菜单',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '/page/menu/menu-add.html',
                    success: function() {
                        var id = $("#id").val();
                        var title = $("#title").val();
                        var href = $("#href").val();
                        var body = layer.getChildFrame('body', index);
                        body.find("input[name='pid']").val(id);
                        body.find("input[name='pidname']").val(title);
                    },
                    end: function () {//无论是确认还是取消，只要层被销毁了，end都会执行，不携带任何参数。layer.open关闭事件
                        Refresh();
                        renderTable();
                    }
                });
                // $(window).on("resize", function () {
                //     layer.full(index);
                // });
            }
        });

    });

    //判断是否有子集
    function hasChildren(menuId, arr) {
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].pid == menuId) {
                return true;
            }
        }
        return false;
    }
    //转化格式递归
    function transData(json, idStr, pidStr, chindrenStr) {
        var r = [], hash = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = json.length;
        for (; i < len; i++) {
            hash[json[i][id]] = json[i];
        }
        for (; j < len; j++) {
            var aVal = json[j], hashVP = hash[aVal[pid]];
            if (hashVP) {
                !hashVP[children] && (hashVP[children] = []);
                hashVP[children].push(aVal);
            } else {
                r.push(aVal);
            }
        }
        return r;
    }
     //刷新
     function Refresh() {
         layui.use(['tree', 'layer','form','table'], function () {
             var form = layui.form,
                 layer = layui.layer,
                 $ = layui.$;
             //清空菜单详情
             $("#myForm").find('input[type=text],input[type=hidden]').each(function () {
                 $(this).val('');
             });
             //重载树形菜单


         });
     }

</script>
    </body>
</html>